#include "db/dimension.h"
#include "db/connection.h"

#include <wx/msgdlg.h>
#include <wx/dbtable.h>

wxString Dimension::tableName()
{
	return wxT("dimension");
}

vector<Dimension> Dimension::getFullList()
{
	wxDb * db = DbConnection::getInstance()->getPointer();
	int id = 0;
	wxChar name[255];

	wxDbTable * table = new wxDbTable(db, Dimension::tableName(), 2, wxT(""), !wxDB_QUERY_ONLY, wxT(""));
	table->SetColDefs(0, wxT("id"), DB_DATA_TYPE_INTEGER, &id,
				SQL_INTEGER, sizeof(id), true, true);
	table->SetColDefs(1, wxT("name"), DB_DATA_TYPE_VARCHAR, name,
                SQL_C_WXCHAR, sizeof(name), true, true);

	if (!table->Open()) {
		DbConnection::handleError(wxT("TABLE OPEN ERROR: "), table->GetDb());
	}
	if (!table->Query()) {
		DbConnection::handleError(wxT("QUERY ERROR: "), table->GetDb());
	}

	vector<Dimension> ret;
	while (table->GetNext()) {
		Dimension item;
		item.ID = id;
		item.name = name;
		ret.push_back(item);
	}
	return ret;
}

bool Dimension::createRecord(const Dimension & record)
{
	wxDb * db = DbConnection::getInstance()->getPointer();
	wxDbTable * table = new wxDbTable(db, Dimension::tableName(), 2, wxT(""), !wxDB_QUERY_ONLY, wxT(""));
	wxChar name[255];
	int id = record.ID;
	wxStrcpy(name, record.name);
	table->SetColDefs(0, wxT("id"), DB_DATA_TYPE_INTEGER, &id,
		SQL_INTEGER, sizeof(id), true, true);
	table->SetColDefs(1, wxT("name"), DB_DATA_TYPE_VARCHAR, name,
		SQL_C_WXCHAR, sizeof(name), true, true);

	if (!table->Open()) {
		DbConnection::handleError(wxT("TABLE OPEN ERROR: "), table->GetDb());
		return false;
	}

	if (!table->Insert()) {
		DbConnection::handleError(wxT("CREATING ERROR: "), table->GetDb());
		table->GetDb()->RollbackTrans();
		return false;
	}
	return table->GetDb()->CommitTrans();
}

bool Dimension::updateRecord(const Dimension & record)
{
	return false;
}

bool Dimension::deleteRecord(const Dimension & record)
{
	wxDb * db = DbConnection::getInstance()->getPointer();
	wxDbTable * table = new wxDbTable(db, Dimension::tableName(), 2, wxT(""), !wxDB_QUERY_ONLY, wxT(""));
	if (!table->DeleteWhere(wxT("id = ") + wxString::Format(wxT("%d"), record.ID))) {
		DbConnection::handleError(wxT("DELETION ERROR: "), table->GetDb());
		table->GetDb()->RollbackTrans();
		return false;
	}
	return table->GetDb()->CommitTrans();
}